<template>
	<!-- 自定义头部导航 -->
	<page-meta>
		<navigation-bar :title="title" front-color="#000000" background-color="#FBFBFF" fixed />
	</page-meta>
	<u-line></u-line>
	<view class="baseForm">
		<u--form labelPosition="left" :model="umodel" :rules="rules" ref="uForm" class="form" labelWidth="160rpx"
			errorType="toast">
			<u-form-item label="外部编号">
				<u--input v-model="umodel.externalCode" inputAlign="right" clearable border="none"
					:disabled='true'></u--input>
			</u-form-item>
            <u-form-item label="物料编号" prop="productionMaterialCode" @click="openMaterialSelect">
				<u--input v-model="umodel.productionMaterialCode" border="none" disabled disabledColor="#ffffff" inputAlign="right"
					placeholder="请选择物料"></u--input>
				<template #right>
					<u-icon name="arrow-right"></u-icon>
				</template>
			</u-form-item>
			<u-form-item label="合格件数" prop="validQuantity">
				<u--input v-model="umodel.validQuantity" placeholder="合格件数" inputAlign="right" clearable
					type = "number"
					:disabled='props.isValid==0' border="none"></u--input>
			</u-form-item>
			<u-form-item label="不合格数" prop="invalidQuantity">
				<u--input v-model="umodel.invalidQuantity" placeholder="不合格数" :disabled='props.isValid==1'
					type = "number"
					inputAlign="right" clearable border="none"></u--input>
			</u-form-item>
<!-- 			<u-form-item label="开工时间" prop="startTime" @click="openTimeSelect">
				{{umodel.startTime}}
				<u--input v-model="umodel.startTime" border="none"  disabled disabledColor="#ffffff" v-if="false"
					placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="show" v-model="umodel.startTimeA" mode="datetime" @cancel="show = false"
					@confirm="timeSelect"></u-datetime-picker>
			</u-form-item>
			<u-form-item label="完工时间" prop="completeTime" @click="openTimeSelect1">
				{{umodel.completeTime}}
				<u--input v-model="umodel.completeTime" border="none"  disabled  v-if="false"
					disabledColor="#ffffff" placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="show1" v-model="umodel.completeTimeA" mode="datetime" @cancel="show1 = false"
					@confirm="timeSelect1"></u-datetime-picker>
			</u-form-item> -->
			<u-form-item label="最大容量" >
				{{quantity}}
			</u-form-item>
			<u-form-item label="已报工数量" v-if="props.sumQuantity > 0">
				{{props.sumQuantity}}
			</u-form-item>
		</u--form>
		<u-picker :show="showmaterial" :columns="materialList" keyName="materialCode" immediateChange @cancel="showmaterial = false"
			@confirm="materialSelect"></u-picker>
		<!-- 提交按钮 -->
		<button type="primary" @click="submit" class="submit_btn" :loading="posting" :disabled="disabled">提 交</button>
		<u-modal
			:show="showReport"
			ref="uModal"
			:content="text"
			confirmText="确认"
			showCancelButton
			@cancel="cancelReport"
			@confirm="confirmReport"
		></u-modal>
		<web-view
			ref="webview"
			id="webview"
			v-if="showWebView"
			:src="webviewSrc"
			:update-title="false"
			allow="*"
			:webview-styles="{
				width: '0px',
				height:'0px',
			}"
			style="height:0px;width:0px;background-color: aquamarine;"
			@message="message"
		></web-view>
	</view>

</template>

<script lang="ts" setup>
	import { useProduceStore } from '../../../stores/useProduceStore';
	import { useUserStore } from '../../../stores/useUserStore';
	import { http } from '../../../utils/http';
	import { getTimes } from '@/utils/common';
	import { computed, reactive, ref } from 'vue';
	// 表单数据定义
	const umodel = reactive({
		workCenterId: '',
		workCenterCode: '',
		workCenterName: '',
		workingFormId: '',
		workingFormCode: '',
		materialId: '',
		materialCode: '',
		validQuantity: '',
		invalidQuantity: '',
		productionMaterialCode:'',
		productionMaterialId:'',
		externalCode: '',
		completeTime: getTimes(Date.now()),
		startTime: getTimes(Date.now()),
		completeTimeA: getTimes(Date.now()),
		startTimeA: getTimes(Date.now()),
		mesMemberLoginRecordDTOS: [],
		crewId: '',
    plannedBatchId: '',
    routingAllocationId: '',
	});
	const showmaterial = ref(false);
	const props = defineProps({
		result: {
			type: String,
			default: '',
		},
		title: {
			type: String,
			default: '',
		},
		isValid: {
			type: String,
			default: "2",
		},
		sumQuantity: {
			type: String,
			default: "0",

		},
	});
	umodel.externalCode = props.result;
	const title = props.title
	const show = ref(false);
	const show1 = ref(false);
	// 登录工作组信息
	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	umodel.workCenterName = loginWorkInfo.value.workCenterName
	umodel.workCenterId = loginWorkInfo.value.workCenterId
	umodel.crewId = loginWorkInfo.value.crewId
	// 加工单信息
	const workOrderList = computed(() => JSON.parse(useProduceStore().workOrderList));
  umodel.workingFormId = workOrderList.value != [] ? workOrderList.value[0]?.id : '';
  umodel.plannedBatchId = workOrderList.value != [] ? workOrderList.value[0]?.id : '';
	umodel.plannedBatchId = workOrderList.value != [] ? workOrderList.value[0]?.id : '';
	umodel.materialId = workOrderList.value != [] ? workOrderList.value[0]?.materialId : '';
	umodel.materialCode = workOrderList.value != [] ? workOrderList.value[0]?.materialCode : '';
	umodel.productionMaterialId = workOrderList.value != [] ? workOrderList.value[0]?.productionMaterialId : '';
  umodel.productionMaterialCode = workOrderList.value != [] ? workOrderList.value[0]?.productionMaterialCode : '';
  umodel.routingAllocationId = workOrderList.value != [] ? workOrderList.value[0]?.routingAllocationId : '';
	console.log(workOrderList.value[0]);
	let materialList = reactive([]);
	materialList[0] = [workOrderList.value[0]?.materialCode]
	// materialList[0] = workOrderList.value[0]?.productionMaterialCodes.map(materialCode => ({
	//   materialCode
	// }));
	
	console.log(materialList[0]);
	//班组登录信息
	let crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	umodel.mesMemberLoginRecordDTOS = crewMemberList.value
	const defaultPrinter = computed(() => JSON.parse(useUserStore().defaultPrinter));
	// console.log(unit)
	// 表单规则定义
	const rules = ref({
		validQuantity: [
			{
				type: 'number',
				message: '请输入数字',
				trigger: ['blur', 'change']
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						//先判断空可以过
						return true;
					} else {
						if (/(^[1-9]\d*$)/.test(value)) {
							//验证正整数和0的正则
							return true;
						} else {
							return false;
						}
					}
				},
				message: '请输入大于0数字或为空',
			},
		],
		invalidQuantity: [
			{
				type: 'number',
				message: '请输入数字',
				trigger: ['blur', 'change']
			},
			{
				validator: (rule, value, callback : (a ?: any) => {}) => {
					if (!value) {
						//先判断空可以过
						return true;
					} else {
						if (/(^[1-9]\d*$)/.test(value)) {
							//验证正整数和0的正则
							return true;
						} else {
							return false;
						}
					}
				},
				message: '请输入大于0数字或为空',
			},
		],
	});
	// 打印日志信息
	const operateLog = ref({
		logLevel: "INFO",
		applicationName: "jcfk-mes",
		modular: "报工开始",
		businessType: "打印",
		info: "",
	})

	// 校验提交
	const uForm = ref();
	const posting = ref(false);
	const url = process.env.VITE_APP_WEBVIEW;
	const showWebView = ref(false);
	const webviewSrc = ref('');
	const resArr = ref([])
	function confirmImport(id) {
		setTimeout(() => {
			insertOperateLog(id, defaultPrinter.value.printerName)
			webviewSrc.value = `${url}iframePrint?id=${id}&printer=${defaultPrinter.value.printerName}&printername=${loginWorkInfo.value.userName}`
			console.log('webviewSrc.value', webviewSrc.value)
			showWebView.value = true;
		}, 1000)
	}
	function openMaterialSelect() {
		showmaterial.value = true;
		uni.hideKeyboard();
	}
	function materialSelect(e) {
		if (e.value.length) {
			umodel.productionMaterialCode = e.value[0].materialCode;
			
		}
		showmaterial.value = false;
		console.log(umodel.productionMaterialCode)
	}
	//开始打印
	async function insertOperateLog(id : any, name : any) {
		operateLog.value.info = id + "," + name
		await http({
			method: 'POST',
			url: '/system/sysOperateLog/insert',
			data: operateLog.value
		});
	}
	let text = ref()
	const disabled = ref(false)
	function submit() {
		const defaultPrinter = computed(() => (useUserStore().defaultPrinter ? JSON.parse(useUserStore().defaultPrinter) : ''));
		console.log("打印机名称:",defaultPrinter.value.printerName);
		if (defaultPrinter.value.length==0)
		{
		uni.showToast({
			title: '请选择打印设备',
			icon: 'error'
		});
		return false;
		}
		else
		{
		uForm.value.validate().then(async (valid : any) => {
			if (umodel.validQuantity == "" && umodel.invalidQuantity == "") {
				if (props.title == "二次报工") {
					uni.$u.toast("该件数不能为空");
					return;
				} else {
					uni.$u.toast("请填写任意一项合格件数和不合格件数");
					return;
				}
			} else {
				let sum = 0
				if (!props.sumQuantity) {
					sum = 0
				} else{
					sum = Number(props.sumQuantity) 
				}
				if (quantity.value > 0){
					// if (quantity.value > 0 && (Number(umodel.validQuantity) + Number(sum) > quantity.value || Number(umodel.invalidQuantity) + Number(sum) > quantity.value)) {
					// 	uni.$u.toast("报工总数量大于指令数量，不可以报工。");
					// } else {
						if(Number(umodel.validQuantity)>0 && !Number(umodel.invalidQuantity) && Number(umodel.validQuantity) == quantity.value){
							reportWork()
						} else if(Number(umodel.invalidQuantity)>0 && !Number(umodel.validQuantity) && Number(umodel.invalidQuantity) == quantity.value){
							reportWork()
						} else if(Number(umodel.validQuantity) == quantity.value && Number(umodel.invalidQuantity) == quantity.value){
							reportWork()
						} else if(Number(umodel.validQuantity)>0 && !Number(umodel.invalidQuantity) && Number(umodel.validQuantity) != quantity.value){
							text.value = `当前包装指令：${quantity.value}，报工合格数量${umodel.validQuantity},确认报工吗?`
							showReport.value = true;
						} else if(Number(umodel.invalidQuantity)>0 && !Number(umodel.validQuantity) && Number(umodel.invalidQuantity) != quantity.value){
							text.value = `当前包装指令：${quantity.value}，报工不合格数量${umodel.invalidQuantity},确认报工吗?`
							showReport.value = true;
						} else {
							text.value = `当前包装指令：${quantity.value}，报工合格数量${umodel.validQuantity}，报工不合格数量${umodel.invalidQuantity},确认报工吗?`
							showReport.value = true;
						}
					// }
				} else {
					// 未设置包装指令不提醒
					// if(Number(umodel.validQuantity) && Number(umodel.invalidQuantity)){
					// 	text.value = `当前报工合格数量${umodel.validQuantity}不合格数量${umodel.invalidQuantity}确认报工吗?`
					// } else if (Number(umodel.validQuantity) && !Number(umodel.invalidQuantity)) {
					// 	text.value = `当前报工合格数量${umodel.validQuantity}确认报工吗?`
					// } else if (!Number(umodel.validQuantity) && Number(umodel.invalidQuantity)){
					// 	text.value = `当前报工不合格数量${umodel.invalidQuantity}确认报工吗?`
					// }
					// showReport.value = true;
					reportWork()
				}
			}
		}).catch((errors) => {
			disabled.value = false;
			posting.value = false;
			console.log(errors);
		})
		}
	}
	//报工
	async function reportWork() {
		posting.value = true;
		disabled.value = true;
		// 请求
		await http({
			method: 'POST',
			url: '/mes/mesproducetransferform/reportingWork',
			data: {
				...umodel
			}
		}).then((res) => {
			if (res.code == "200") {
				countdown(6)
				posting.value = false;
				// 检查 data 是否为数组
				if (Array.isArray(res.data)) {
					confirmImport(res.data[0].id);
					if (res.data.length > 1) {
						resArr.value = res.data
					}
					uni.$u.toast(`报工成功!`);
					// setTimeout(() => { // 临时加载耗时，待后期webview通信成功后优化
					// 	uni.switchTab({
					// 		url: '/pages/index/index'
					// 	})
					// }, 5 * 1000)
				} else {
					console.error('返回的数据不是数组');
				}
			} else {
				disabled.value = false;
				posting.value = false;
			}
		})
		// disabled.value = false;
		posting.value = false;
	}
	const showReport = ref(false);
async function confirmReport() {
	showReport.value = false;
	reportWork()
}
	
	// 取消选择订单
	function cancelReport() {
		showReport.value = false;
	}
	getDefaultValue()
	//获取默认数量
	const quantity = ref();
	async function getDefaultValue() {
		await http({
			method: 'POST',
			url: '/wms/wmspackagecmd/getList',
			data: {
				materialId: umodel.productionMaterialId,
				applicableScenario: 5,
			}
		}).then((res) => {
			if (res.data[0]?.quantity >= 0) {
				if (props.isValid == '2') {
					umodel.validQuantity = res.data[0].quantity
				}
				quantity.value = res.data[0].quantity
			} else {
				umodel.validQuantity = 0
				quantity.value = 0
			}
		})
	}
	// 时间选择
	function timeSelect(e) {
		console.log(e);
		umodel.startTimeA = e.value
		umodel.startTime = getTimes(e.value);
		console.log(umodel.startTime);
		show.value = false;
	}
	function timeSelect1(e) {
		console.log(e);
		umodel.completeTimeA = e.value
		umodel.completeTime = getTimes(e.value);
		console.log(umodel.completeTime);
		show1.value = false;
	}
	function openTimeSelect() {
		show.value = true;
		uni.hideKeyboard();
	}
	function openTimeSelect1() {
		show1.value = true;
		uni.hideKeyboard();
	}
	const time = ref()
	let flag = ref(true)
	function countdown(seconds) {
		time.value=seconds
	  if (time.value >= 1) {
	    console.log(time.value);
		uni.$u.toast(`报工成功,正在打印,还剩${time.value}秒关闭页面,在此期间请勿进行其他操作否则影响打印!`);
	    setTimeout(function() {
			if(flag.value){
				countdown(time.value - 1);
			}
	    }, 1000);
	  } else {
	    console.log("倒计时结束");
	  }
	}
	// webview向外部发送消息
	function message(event) {
		console.log("event",event)
		const data:any = event.detail.data[0];
		//清空数据
		showWebView.value = false;
		console.log(data)
		// if(Array.isArray(resArr.value) && (resArr.value.length == 0)){
		// 	resArr.value = ''
		// }
		if (data.code === 200) {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
			console.log("resArr.value.length",resArr.value.length)
			if (resArr.value.length > 1) {
				confirmImport(resArr.value[1].id)
				resArr.value = []
			}else{
				flag.value = false
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		} else {
			uni.showToast({
				icon: 'none',
				title:data.message,
			})
			flag.value = false
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
		// if(!Array.isArray(resArr.value)){
		// 	console.log("返回首页")
		// 	flag.value = false
		// 	uni.switchTab({
		// 		url: '/pages/index/index'
		// 	})
		// }
		console.log("接收到消息1：" + JSON.stringify(event.detail.data));
	}
</script>

<style lang="scss">
	.baseForm {
		.form {
			padding: $uni-page-padding;
		}

		.u-form-item {
			min-height: 46px;
		}

		:deep(.uicon-arrow-right) {
			top: 1px;
			margin-left: 3px;
		}

		.submit_btn {
			margin: 60rpx;
			border-radius: 60rpx;
		}

		:deep(.u-form-item__body__right__content__slot) {
			flex-direction: row-reverse;
		}

		:deep(.u-textarea__field) {
			text-align: right;
		}

		.u-textarea {
			border: 1px solid $uni-input-border-color;
			border-radius: 8px;
		}
	}
</style>